package p.ithorns.tools.serializer;

import org.apache.fury.Fury;
import org.apache.fury.ThreadSafeFury;
import org.apache.fury.config.CompatibleMode;
import org.apache.fury.config.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * FurySerializer
 *
 * @author HtL
 * @date 2024/7/2 8:48
 * @since 1.0.0
 */
public class FurySerializer {

    private final static Logger log = LoggerFactory.getLogger(FurySerializer.class);

    private final static ThreadSafeFury FURY = Fury.builder()
            .withLanguage(Language.JAVA)
            // 是否开启循环引用，如果并不需要的话可以关闭，提升性能
            // .withRefTracking(true)
            .requireClassRegistration(false)
            // 是否压缩 Integer 或者 Long 类型的数字
            // .withNumberCompressed(true)
            // 类型前后一致性兼容
            .withCompatibleMode(CompatibleMode.SCHEMA_CONSISTENT)
            // .withAsyncCompilation(true)
            .buildThreadSafeFury();


    public static byte[] serialize(Object obj) {
        return FURY.serialize(obj);
    }

    public static Object deserialize(byte[] bytes) {
        try {
            return FURY.deserialize(bytes);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static <T> T deserialize(byte[] bytes, Class<T> clazz) {
        return FURY.deserializeJavaObject(bytes, clazz);
    }


    public static String deserializeString(byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8);
    }

}